﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using SmsCovert.Service;
using System.Net.NetworkInformation;
using System.IO;
using System.Diagnostics;

namespace SmsCovert
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }

        Socket s = null;        //服务器Socket
        Socket temp = null;     //客户端Socket
        Thread td;              //接收线程
        string Info = "";       //发送信息内容
        string PhoneNo = "";    //电话号码
        string ConfirmNo = "";  //确认码
        string MessageID = "";  //短信id
        bool flag = true;       //标志
        LOG log = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            log = new LOG(DateTime.Now);
            if (!log.IsNormal())
            {
                MessageBox.Show("程序异常");
            }
            log.LogWrite(DateTime.Now);
            int restDays = log.restDays();
            if (restDays > 0)
            {
                MessageBox.Show("您还有" + log.restDays() + "天试用时间.");
            }
            else
            {
                MessageBox.Show("您好，你的试用期已经结束喽!请购买正版.");
                System.Environment.Exit(0);
            }



            Control.CheckForIllegalCrossThreadCalls = false;
            ReceiveSocket();
        }



        /// <summary>开一个Socket监听线程
        ///
        /// </summary>
        private void ReceiveSocket()
        {
            this.lblStatus.ForeColor = Color.Green;
            this.lblStatus.Text = "已启动";
            this.lblLinkStatus.Text = "服务已启动...\r\n";
            this.lblLinkStatus.Text += "正在等待接收数据...\r\n";
            MoveToLast();

            IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 1234);
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建一个Socket类
            s.Bind(ipe); //绑定端口
            s.Listen(10);//开始监听

            td = new Thread(new ThreadStart(listener));
            td.Start();
        }

        /// <summary>监听线程
        /// 
        /// </summary>
        protected void listener()
        {
            while (flag)
            {
                try
                {
                    if (temp == null)
                    {
                        temp = s.Accept();//为新建连接创建新的Socket
                    }

                    IPEndPoint clientip = (IPEndPoint)temp.RemoteEndPoint;

                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                    recvStr = Encoding.Unicode.GetString(recvBytes, 0, bytes);

                    showStatus(clientip.Address.ToString(), clientip.Port.ToString(), recvStr);//显示信息
                    MoveToLast();

                    byte[] sendContent = Encoding.Unicode.GetBytes("1:SMS send OK!\r\n"); //回复ITU表示收到
                    temp.Send(sendContent);

                }
                catch (Exception e)
                {
                    if (temp != null)
                    {
                        temp.Shutdown(SocketShutdown.Both);
                        temp.Close();
                        temp = null;
                    }
                }
            }
        }


        /// <summary>显示这些状态
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="content"></param>
        private void showStatus(string ip, string port, string content)
        {
            if (content == string.Empty) return;
            analysis(content);
            this.lblIP.Text = ip;
            this.lblPort.Text = port;
            this.lblLinkStatus.Text += DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n";
            this.lblLinkStatus.Text += "IP:" + ip + "    ";
            this.lblLinkStatus.Text += "Port:" + port + "\r\n";

            this.lblLinkStatus.Text += "发送电话：" + PhoneNo + "\r\n";
            this.lblLinkStatus.Text += "发送内容:" + Info + "\r\n";
            this.lblLinkStatus.Text += "确认码:" + ConfirmNo + "\r\n";
            this.lblLinkStatus.Text += "正在发送...\r\n";
            MoveToLast();
            //if (IsSent())
            //{
            //    this.lblLinkStatus.Text += "信息发送成功.\r\n\r\n";
            //}
            //else
            //{
            //    this.lblLinkStatus.Text += "发送失败.\r\n\r\n";
            //}

        }

        /// <summary>解析接收的内容
        /// 
        /// </summary>
        /// <param name="str">接收的字符串</param>
        private void analysis(string str)
        {

            PhoneNo = str.Substring(3, int.Parse(str.Substring(1, 2)));
            int index = str.IndexOf("确认码");

            if (index < 0)
            {
                ConfirmNo = "无确认码";
                Info = str.Substring(3 + int.Parse(str.Substring(1, 2)));
            }
            else
            {
                ConfirmNo = str.Substring(index + 4);
                Info = str.Substring(3 + int.Parse(str.Substring(1, 2)), index - 3 - int.Parse(str.Substring(1, 2)));
            }

        }

        #region 托盘图标
        private void noIcon_MouseClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
        }

        private void label2_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
        #endregion


        /// <summary>移动光标到最后
        /// </summary>
        protected void MoveToLast()
        {
            this.lblLinkStatus.Select(this.lblLinkStatus.TextLength, 0);
            this.lblLinkStatus.ScrollToCaret();
        }



        /// <summary>短信是否发送成功
        /// </summary>
        /// <returns></returns>
        //protected bool IsSent()
        //{
        //    SendMsg sm = new SendMsg(PhoneNo, Info);
        //    string IsSuccess = sm.Send();
        //    if (IsSuccess == "true")
        //    {
        //        MessageID = IsSuccess;
        //        return true;
        //    }
        //    else
        //    {
        //        return false;
        //    }

        //}

        private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否要退出？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
            {
                flag = false;
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Math.Abs(log.Worning()) > 1)
            {
                MessageBox.Show("非法操作!程序即将退出!");
                System.Environment.Exit(0);
            }
        }

    }
}
